package api

import (
	"gitee.com/alex_li/upload/internal/etc"
	"github.com/lishimeng/app-starter/server"
	"github.com/lishimeng/go-log"
	"io"
	"mime/multipart"
	"os"
	"path/filepath"
)

func uploadMultiple(ctx server.Context) {

	var resp MultipleUploadResponse

	log.Debug("upload multi")

	err := ctx.C.Request().ParseMultipartForm(etc.Config.Upload.MaxSize << 20)
	if err != nil {
		resp.Code = 500
		ctx.Json(resp)
		return
	}
	form := ctx.C.Request().MultipartForm
	files := form.File["files[]"]
	failures := 0
	for _, file := range files {
		subFile := genTmpFileName(file.Filename)
		dest := etc.Config.Upload.Root + subFile
		_, err = saveUploadedFile(file, dest)
		success := true
		if err != nil {
			failures++
			success = false
		}
		resp.Items = append(resp.Items, FileResponse{
			Success: success,
			File:    subFile,
			Name:    file.Filename,
		})
	}
	resp.Code = 0
	resp.Success = len(files) - failures
	resp.Fail = failures
	ctx.Json(resp)
}

func saveUploadedFile(fh *multipart.FileHeader, dest string) (int64, error) {
	src, err := fh.Open()
	if err != nil {
		return 0, err
	}
	defer func() {
		_ = src.Close()
	}()
	out, err := os.OpenFile(filepath.Join(dest),
		os.O_WRONLY|os.O_CREATE, os.FileMode(0666))
	if err != nil {
		return 0, err
	}
	defer func() {
		_ = out.Close()
	}()
	return io.Copy(out, src)
}
